<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Login extends Controller
{
    public function index()
    {
        if (Request::instance()->Post()) {
            $username = trim(input('post.username'));
            $password = trim(input('post.password'));
            $verify = trim(input('post.verify'));

            if (!$username || !$password || !$verify) {
                $this->error(config('msg.1001'));
            }

            if (!captcha_check($verify)) {
                $this->error(config('msg.1002'), 'index');
            }

            $info = model('admin_user')->field('id,uname,password')->where('uname', $username)->find();

            if (!$info) {
                $this->error(config('msg.1001'), 'index');
            }

            if (md5($password) != $info['password']) {
                $this->error(config('msg.1001'), 'index');
            }

            //记录登陆信息
            $time = time();
            $ip = inet_aton(Request::instance()->ip());
            $browser = browser_info();
 
            $res = model('login_log')->save([
                'uid' => $info['id'],
                'login_time' => $time,
                'login_ip' => $ip,
                'browser' => $browser,
            ]);
            
            if ($res === false) {
                $this->error('登录失败, 请稍后重试');
            }
            session('uname', $info['uname']);
            session('uid', $info['id']);

            $this->success('登入成功', 'index/index');
        } else {
            if (session('?user_name')) {
                return $this->success('您已登入', 'index/home');
            } else {
                return  $this->fetch();
            }
        }
    }

    /**
    * 登出
    */
    public function logout()
    {
        session(null);
        return $this->success('成功退出', 'login/index');
    }
}
